"""
Author: Meng
Date: 2018/11/10
"""
from app.models.square.topic import Topics, TopicComment, CommentReply
from app.models.admin.user import User
from flask_restful import Resource, reqparse, fields
from app.api import api
from f_lib.principal.auth import auth_token
from f_lib.code import Msg
from flask import g, make_response, Response
import os
from settings import THUMB_IMG
from f_lib.marshal_list import marshal


class CreateComment(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('topic_id', required=True, type=int)
    parse.add_argument('content', required=True, type=str)

    @auth_token()
    def post(self):
        arg = self.parse.parse_args()
        topic = Topics.get_by_id(arg['topic_id'])
        if topic:
            cc = topic.comment_count
            idx = cc + 1 if cc else 1
            topic.update(comment_count=idx)
            comment = TopicComment(from_uid=g.user.id, from_name=g.user.name, idx=idx, **arg)
            comment.save()
        return Msg.success()


class DeleteComment(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('id')

    @auth_token()
    def post(self):
        arg = self.parse.parse_args()
        comment = TopicComment.query_one(**arg)
        if comment:
            if comment.from_uid == g.user.id:
                comment.delete()
            else:
                return Msg.failed_dict(7000)
        return Msg.success()


class CreateCommentReply(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('comment_id', required=True, type=int)
    parse.add_argument('reply_id', required=True, type=int)
    parse.add_argument('reply_type', required=True, type=str, choices=('comment', 'reply'))
    parse.add_argument('to_uid', required=True, type=int)
    parse.add_argument('content', required=True, type=str)

    @auth_token()
    def post(self):
        arg = self.parse.parse_args()
        comment = TopicComment.get_by_id(arg['comment_id'])

        if comment:
            cr = comment.reply_count
            idx = cr + 1 if cr else 1
            comment.update(reply_count=idx)
            reply_idx = idx
            if arg['reply_type'] == 'reply':
                rly = CommentReply.get_by_id(arg['reply_id'])
                if rly:
                    reply_idx = rly.idx
            reply = CommentReply(from_name=g.user.name, from_uid=g.user.id, idx=idx, reply_idx=reply_idx, **arg)
            reply.save()
        return Msg.success()


class DeleteReply(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('id', type=int, required=True)

    @auth_token()
    def post(self):
        arg = self.parse.parse_args()
        reply = CommentReply.query_one(**arg)
        if reply:
            if reply.from_uid == g.user.id:
                reply.delete()
            else:
                return Msg.failed_dict(7000)
        return Msg.success()


class CommentList(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('topic_id', required=True, type=int)
    parse.add_argument('order', type=str, choices=('desc', 'asc'), required=True)
    comment_field = dict(
        id=None,
        from_uid=None,
        from_name=None,
        content=None,
        time=None,
        idx=None,
        like=None,
    )
    reply_field = dict(
        id=None,
        from_uid=None,
        from_name=None,
        to_uid=None,
        ctime=None,
        content=None,
        reply_id=None,
        reply_type=None,
        idx=None,
        like=None,
        reply_idx=None
    )

    def get(self):
        arg = self.parse.parse_args()
        comments = TopicComment.query_where_many(params=list(self.comment_field.keys()),
                                                 wheres=['topic_id={}'.format(arg['topic_id'])],
                                                 order=['id', arg['order']])
        co = []
        if comments:
            for comment in comments:
                comment_m = marshal(self.comment_field, comment)
                comment_m['reply'] = []

                replys = CommentReply.query_many(comment_id=comment.id)
                if replys:
                    for reply in replys:
                        reply_m = marshal(self.reply_field, reply)
                        reply_m['to_name'] = User.get_by_id(reply.to_uid).name
                        if reply.reply_type == 'reply':
                            reply_m['reply_content'] = CommentReply.get_by_id(reply.reply_id).content
                        comment_m['reply'].append(reply_m)
                co.append(comment_m)
        return Msg.success(comments=co)


class LikeC(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('reply_type', required=True, type=str, choices=('comment', 'reply'))
    parse.add_argument('id', required=True, type=int)
    parse.add_argument('like', required=True, type=int, choices=(1, 0))

    @auth_token()
    def post(self):
        arg = self.parse.parse_args()
        if arg['reply_type'] == 'comment':
            comment = TopicComment.get_by_id(arg['id'])
            if comment:
                like = comment.like
                dislike = comment.dislike
                if arg['like'] == 1:
                    l = like + 1 if like else 1
                    comment.update(like=l)
                elif arg['like'] == 0:
                    l = dislike + 1 if dislike else 1
                    comment.update(dislike=l)
                return Msg.success()
            return Msg.failed_dict(1003)
        elif arg['reply_type'] == 'reply':
            reply = CommentReply.get_by_id(arg['id'])
            if reply:
                like = reply.like
                dislike = reply.dislike
                if arg['like'] == 1:
                    l = like + 1 if like else 1
                    reply.update(like=l)
                elif arg['like'] == 0:
                    l = dislike + 1 if dislike else 1
                    reply.update(dislike=l)
                return Msg.success()
            return Msg.failed_dict(1003)
        return Msg.failed_dict(1003)


api.add_resource(CommentList, '/topic/comment/list', endpoint='comment_list')
api.add_resource(CreateComment, '/topic/comment/add', endpoint='comment_add')
api.add_resource(DeleteComment, '/topic/comment/del', endpoint='comment_del')
api.add_resource(LikeC, '/topic/comment/like', endpoint='like_comment')
api.add_resource(CreateCommentReply, '/topic/reply/add', endpoint='reply_add')
api.add_resource(DeleteReply, '/topic/reply/del', endpoint='reply_del')
